import java.util.ArrayList;
import java.util.List;

class Solution {
    public List<String> restoreIpAddresses(String s) {
        List<String> result = new ArrayList<>();
        List<String> current = new ArrayList<>();
        backtrack(s, 0, current, result);
        return result;
    }

    private void backtrack(String s, int index, List<String> current, List<String> result) {
        if (current.size() == 4) {
            if (index == s.length()) {
                result.add(String.join(".", current));
            }
            return;
        }

        for (int i = 1; i <= 3; i++) {
            if (index + i > s.length()) {
                break;
            }
            String segment = s.substring(index, index + i);
            if (isValidSegment(segment)) {
                current.add(segment);
                backtrack(s, index + i, current, result);
                current.remove(current.size() - 1);
            }
        }
    }

    private boolean isValidSegment(String segment) {
        if (segment.length() > 1 && segment.charAt(0) == '0') {
            return false;
        }
        int num = 0;
        for (int i = 0; i < segment.length(); i++) {
            char c = segment.charAt(i);
            if (!Character.isDigit(c)) {
                return false;
            }
            num = num * 10 + (c - '0');
        }
        return num >= 0 && num <= 255;
    }
}
